<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chat</title>
</head>
<body>
<div id="loginDiv">
    <input id="uid" type="text"/><br/>
    <input id="loginBtn" type="button" value="登录" onclick="login()"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input id="logoutBtn" type="button" value="退出"/><br/><br/>

    <input id="say" type="text"/><br/>
    <input id="sayBtn" type="button" value="发言"/><br/>
</div>

<div id="container">

</div>

<script>
    var url = "ws://localhost:8080/chat";
    var ws;

    function login() {
        var uid = document.getElementById("uid").value;
        //登入、登出消息
        var messageIn = {
            type: 1,
            uid: uid
        }
        var messageOut = {
            type: 2,
            uid: uid
        }

        ws = new WebSocket(url)

        ws.onopen = function (event) {
            ws.send(JSON.stringify(messageIn))
            console.log("open")
        }

        /**
         * 经测试，浏览器端刷新页面，或关闭页面时，onclose和onerror没机会执行（因为页面关闭或刷新,websocket对象已销毁）
         * websocket服务端下线时，才会执行
         * @param ev
         */
        ws.onclose = function (event) {
            console.log("close")
        }
        ws.onerror = function (event) {
            console.log("error")
            ws.close(3001, "error")
        }

        ws.onmessage = function (event) {
            var p = document.createElement("p");
            p.innerText = event.data
            document.getElementById("container").appendChild(p)
        }

        var logoutBtn = document.getElementById("logoutBtn");
        logoutBtn.onclick = function () {
            ws.send(JSON.stringify(messageOut))
            ws.close(3002, "logout")
        }

        var sayBtn = document.getElementById("sayBtn")
        sayBtn.onclick = function () {
            var say = document.getElementById("say").value;
            //发言消息
            var messageSay = {
                type: 3,
                uid: uid,
                text: say
            }

            ws.send(JSON.stringify(messageSay))
        }
    }
</script>
</body>
</html>